package ro.gateway.aida.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.db.DBFilesPersMan;
import ro.gateway.aida.db.DBPersistenceToken;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.obj.AIDADocument;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.utils.HttpUtils;
import ro.xblue.translator.LanguageBean;
import ro.xblue.translator.TranslatorUtils;

import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;


/**
 * Created by IntelliJ IDEA. User: xblue Date: Mar 2, 2004 Time: 7:02:43 PM To change this template use Options | File
 * Templates.
 */
public class UploadDocServlet extends HttpServlet {
     /**
      *
      */
     public void doGet( HttpServletRequest request,
                        HttpServletResponse response )
        throws IOException, ServletException {
     }

     /**
      *
      */
     public void doPost( HttpServletRequest request,
                         HttpServletResponse response )
        throws IOException, ServletException {
          HttpSession session = request.getSession();

          Hashtable file_parts = new Hashtable();
          Hashtable para_parts = new Hashtable();
          synchronized ( session ) {

               MultipartParser parser = null;
               try {
                    parser = new MultipartParser( request, 10 * 1024 * 1024 );
               } catch ( IOException ioEx ) {

                    return;
               }


               Part part = null;
               while ( ( part = parser.readNextPart() ) != null ) {
                    if ( part.isParam() ) {
                         para_parts.put( part.getName(), ( ( ParamPart ) part ).getStringValue() );
                    } // if param
                    else if ( part.isFile() ) {
                         FilePart filePart = ( FilePart ) part;
                         File file = File.createTempFile( "AIDA-", ".tmp" );
                         filePart.writeTo( file );

                         if ( file.length() == 0 ) {
                              file = null;
                              filePart = null;
                         } else {
                              file_parts.put( filePart.getName(), new Object[]
                              {filePart.getFileName(), file} );
                         }
                    } // is file
               } // while

          }

          String action = HttpUtils.getValidTrimedString( ( String ) para_parts.get( "action" ), null );
          String key = HttpUtils.getValidTrimedString( (
             String ) para_parts.get( "key" ), null );
          Hashtable ed_ctxs = ( Hashtable ) session
             .getAttribute( EditActivityServlet.ED_CTXS );
          Hashtable ctx = ( key != null && ed_ctxs != null ) ?
             ( Hashtable ) ed_ctxs.get( key ) : null;
          Activity activity = ( ctx != null ) ?
             ( Activity ) ctx.get( EditActivityServlet.PNAME_BEAN ) : null;
          LanguageBean lang = TranslatorUtils
             .getCurrentLanguage( request, this.getServletContext() );

          if ( key == null || activity == null ||
             ( ( !"save".equals( action ) ) && ( !"cancel_create".equals( action ) ) ) ) {
               System.err.println( "\t\t\tillegal!!" );
               response.sendRedirect( request.getContextPath() +
                  "/activity/editorcomps/close_me.jsp" );
               return;
          }

//            System.out.println( "uploading action:" + action );

          if ( "save".equals( action ) ) {
               ArrayList items = activity.getDocsList();
               int idx = items.size() - 1;
               AIDADocument document = ( AIDADocument ) items.get( idx );
               String desc = ( String ) para_parts.get( "description" + idx );
               String title = ( String ) para_parts.get( "title" + idx );
               Object[] file_objs = ( Object[] ) file_parts.get( "xfile" + idx );

               DBPersistenceToken token = ( DBPersistenceToken ) PersistenceManager.
                  tokenLookup( getServletContext() );
               DBFilesPersMan files_p_man = DBFilesPersMan.getManager( token );

               if ( file_objs != null ) {
                    try {
                         File zafile = ( File ) file_objs[ 1 ];
                         String file_name = ( String ) file_objs[ 0 ];

                         String dest_rel_path = "/documents/" + file_name;
                         if ( files_p_man.exists(dest_rel_path) ) {
                              int i = 0;
                              dest_rel_path = "/documents/" + i + file_name;
                              while ( files_p_man.exists(dest_rel_path) ) {
                                   i++;
                                   dest_rel_path = "/documents/" + i + file_name;
                              }
                         }

                         files_p_man.saveFile( dest_rel_path, zafile);
                         zafile.delete();

                         document.setDesc( lang.language, desc );
                         document.setTitle( lang.language, title );
                         document.setRelativeLink( dest_rel_path );
                         document.setName( file_name );
                    } catch ( Exception ex ) {
                         ex.printStackTrace();
                    }
               }
          } else if ( "cancel_create".equals( action ) ) {
               ArrayList items = activity.getDocsList();
               if ( items.size() > 0 ) {
                    items.remove( items.size() - 1 );
               }
               response.sendRedirect( request.getContextPath() +
                  "/activity/editorcomps/close_me.jsp" );
               return;
          }

          response.sendRedirect( request.getContextPath() +
             "/activity/editorcomps/close_me.jsp" );
     }
}

